package com.module.my.view

import android.content.Intent
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import com.module.app.arouter.ArouterUtils
import com.module.app.arouter.service.ILauncherService
import com.module.app.arouter.service.ILoginService
import com.module.app.base.BaseActivity
import com.module.app.ext.modifyUserFlow
import com.module.app.pop.CommonPop
import com.module.app.utils.GlideUtils
import com.module.app.utils.UserUtils
import com.module.app.widget.ShowSendView
import com.module.app.bean.IType
import com.module.base.picker.getOptionsPickerView
import com.module.base.utils.*
import com.module.base.utils.imagepicker.CommonImagePickerUtils
import com.module.app.widget.keyboard.InputBuilder.OnMyClickListener
import com.module.app.widget.keyboard.InputConfirmDialog
import com.bigkoo.pickerview.view.OptionsPickerView
import com.module.frame.ext.observe
import com.module.my.R
import com.module.my.bean.UserSexBean
import com.module.my.databinding.MyUserInfoBinding
import com.module.my.model.UserInfoViewModel
import com.module.third.ext.qqLoginSharedFlow
import com.module.third.ext.wxLoginSharedFlow
import com.module.third.qq.QQUtils
import com.module.third.wx.WxUtils
import org.apache.commons.lang3.StringUtils

class UserInfoActivity : BaseActivity<UserInfoViewModel, MyUserInfoBinding>() {

    private var modifyNameDialog: com.module.app.widget.keyboard.InputConfirmDialog? = null

    //验证码弹窗视图
    private var showSendView: com.module.app.widget.ShowSendView? = null

    private val mLoginService: com.module.app.arouter.service.ILoginService by lazy {
        com.module.app.arouter.ArouterUtils.getLoginService()
    }

    private val mLauncherService: com.module.app.arouter.service.ILauncherService by lazy {
        com.module.app.arouter.ArouterUtils.getLauncherService()
    }

    private val qqUtils: QQUtils by lazy { QQUtils(lifecycle) }
    private val wxUtils: WxUtils by lazy { WxUtils(this, lifecycle) }
    override fun bingViewModel() {
        mDatabind.vm = mViewModel
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.my_user_title)
        setRightText(R.string.my_log_off, View.OnClickListener { logOff() })
    }

    override fun initListener() {
        super.initListener()
        //微信登录
        observe(wxLoginSharedFlow) {
            it?.let {
                mViewModel.binding(com.module.app.bean.IType.ILogin.WX, it.openid, it.headimgurl)
            }
        }
        //qq登录
        observe(qqLoginSharedFlow) {
            it?.let {
                mViewModel.binding(com.module.app.bean.IType.ILogin.QQ, it.openid, it.figureurlQq2)
            }
        }
        //修改用户信息
        observe(modifyUserFlow) {
            if (modifyNameDialog != null) {
                modifyNameDialog?.hide()
            }
            setData()
        }
        observe(mViewModel.logoutFlow) {
            logoutSuc()
        }
        observe(mViewModel.verifyCodeFlow) {
            verifyCodeSuc(it)
        }
        observe(mViewModel.logOffFlow) {
            if (it) {
                logOffSuc()
            } else {
                ToastUtils.showShort("注销失败")
            }
        }
    }

    override fun initData() {
        super.initData()
        setData()
        mViewModel.getUser()
    }

    private fun setData() {
        if (StringUtils.isBlank(com.module.app.utils.UserUtils.getHeadUrl())) {
            mDatabind.ivHead.setImageResource(if (com.module.app.utils.UserUtils.getSex() == com.module.app.bean.IType.ISex.male) R.drawable.my_icon_male else R.drawable.my_icon_female)
        } else {
            com.module.app.utils.GlideUtils.loadNet(
                mDatabind.ivHead.context,
                mDatabind.ivHead,
                com.module.app.utils.UserUtils.getHeadUrl()
            )
        }
        mDatabind.tvName.text = com.module.app.utils.UserUtils.getName()
        mDatabind.tvSex.text = com.module.app.utils.UserUtils.getSexStr()
        mDatabind.tvPhone.text = com.module.app.utils.UserUtils.getPhone()
        mDatabind.tvWx.text = if (com.module.app.utils.UserUtils.getWx()
                .isNullOrEmpty()
        ) "" else CommonUtils.getString(R.string.my_binding)
        mDatabind.tvQq.text = if (com.module.app.utils.UserUtils.getQQ()
                .isNullOrEmpty()
        ) "" else CommonUtils.getString(R.string.my_binding)
        mDatabind.tvInvite.text = com.module.app.utils.UserUtils.getInviteCount().toString() + "人"
    }

    fun onClickName(view: View) {
        if (modifyNameDialog == null) {
            modifyNameDialog = com.module.app.widget.keyboard.InputConfirmDialog.Builder(getContext())
                .setTitle(R.string.my_user_name_title)
                .setEditHint(R.string.my_user_name_hint)
                .setConfirmButton(R.string.confirm)
                .setMaxLength(8)
                .setOnConfirmListener(object : OnMyClickListener() {
                    override fun onClick(dialog: com.module.app.widget.keyboard.InputConfirmDialog, text: String) {
                        if (text.isNullOrEmpty()) {
                            ToastUtils.showShort(R.string.my_user_name_empty)
                            return
                        }
                        mViewModel.modifyName(text)
                    }
                }).create()
        }
        modifyNameDialog?.show()
    }

    fun onClickSex(view: View) {
        val lists: MutableList<UserSexBean> = mutableListOf()
        lists.add(UserSexBean(com.module.app.bean.IType.ISex.male, "男"))
        lists.add(UserSexBean(com.module.app.bean.IType.ISex.female, "女"))
        val picker: OptionsPickerView<UserSexBean> =
            getOptionsPickerView<UserSexBean>(this) { options1, options2, options3, v ->
                mViewModel.modifySex(lists[options1].sex)
            }
        picker.setPicker(lists)
        picker.show()
    }


    fun onClickPhone(view: View) {
        if (TextUtils.isEmpty(com.module.app.utils.UserUtils.getPhone())) {
            val dialog = com.module.app.widget.keyboard.InputConfirmDialog.Builder(getContext())
                .setTitle(R.string.my_binding_phone)
                .setEditHint(R.string.my_binding_phone_hint)
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .setConfirmButton(R.string.confirm)
                .setOnConfirmListener(object : OnMyClickListener() {
                    override fun onClick(dialog: com.module.app.widget.keyboard.InputConfirmDialog, text: String) {
                        if (text.isNotBlank()) {
                            ToastUtils.showShort(R.string.my_binding_phone_empty)
                            return
                        }
                        dialog.hide()
                        showCodeDialog(text)
                    }
                }).create()
            dialog.show()
        } else {
            com.module.app.pop.CommonPop.Builder(getContext())
                .setContent(R.string.my_unbinding_title)
                .setCancelButton(R.string.cancel)
                .setConfirmButton(R.string.confirm)
                .setOnConfirmListener { mViewModel.unbinding(com.module.app.bean.IType.ILogin.PHONE) }
                .show()
        }
    }


    fun onClickQQ(view: View) {
        if (TextUtils.isEmpty(com.module.app.utils.UserUtils.getQQ())) {
            qqUtils.login()
        } else {
            com.module.app.pop.CommonPop.Builder(getContext())
                .setContent(R.string.my_unbinding_title)
                .setCancelButton(R.string.cancel)
                .setConfirmButton(R.string.confirm)
                .setOnConfirmListener { mViewModel.unbinding(com.module.app.bean.IType.ILogin.QQ) }
                .show()
        }
    }

    fun onClickWx(view: View) {
        if (TextUtils.isEmpty(com.module.app.utils.UserUtils.getWx())) {
            wxUtils.login()
        } else {
            com.module.app.pop.CommonPop.Builder(getContext())
                .setContent(R.string.my_unbinding_title)
                .setCancelButton(R.string.cancel)
                .setConfirmButton(R.string.confirm)
                .setOnConfirmListener { mViewModel.unbinding(com.module.app.bean.IType.ILogin.WX) }
                .show()
        }
    }

    fun onClickLogout(view: View) {
        mViewModel.logout()
    }

    fun onClickUser(view: View) {
        CommonImagePickerUtils.showSingleCircleImage(getActivity())
    }

    fun onClickInvite(view: View) {
    }


    /**
     * 弹出验证码
     */
    fun showCodeDialog(phone: String) {
        if (showSendView == null) {
            showSendView = com.module.app.widget.ShowSendView(phone)
            showSendView?.setListener(object : com.module.app.widget.ShowSendView.Listener {
                override fun onSend(phone: String) {
                    //发送验证码
                    mViewModel.sendCode(phone)
                }

                override fun onSubmit(code: String) {
                    //验证验证码是否正常
                    mViewModel.verifyCode(phone, code)
                }

                override fun hide() {}
            })
        }
        showSendView?.show()
    }

    private fun verifyCodeSuc(phone: String) {
        if (showSendView != null) {
            showSendView?.hide()
        }
        mViewModel.binding(com.module.app.bean.IType.ILogin.PHONE, phone, null)
    }

    private fun logoutSuc() {
        //返回首页
        if (mLauncherService != null) {
            mLauncherService.startMain(getContext())
        }
        //退出登录
        if (mLoginService != null) {
            mLoginService.logout()
            mLoginService.startLogin(getContext())
        }
    }

    private fun logOff() {
        com.module.app.pop.CommonPop.Builder(getContext())
            .setContent(R.string.my_log_off_content)
            .setContentGravity(Gravity.LEFT)
            .setCancelButton(R.string.my_think)
            .setConfirmButton(R.string.my_log_off)
            .setOnConfirmListener { mViewModel.logOff() }
            .show()
    }

    /**
     * 注销
     */
    private fun logOffSuc() {
        logoutSuc()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        qqUtils.onActivityResult(requestCode, resultCode, data)
        if (CommonImagePickerUtils.onActivityResult(requestCode, resultCode)) {
            // 相册结果回调
            val list = CommonImagePickerUtils.getList(data)
            if (CollectionUtil.isEmptyOrNull(list)) {
                return
            }
            val headUrl = list[0].cutPath
            mViewModel.modifyHead(headUrl)
        }
    }
}